package com.jtny.nytb.config.varible.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.jtny.component.core.util.PageUtils;
import com.jtny.component.core.util.QueryWrapperUtils;
import com.jtny.component.entity.PageData;
import com.jtny.component.exception.ServiceException;
import com.jtny.component.util.Assert;
import com.jtny.component.util.BeanUtils;
import com.jtny.nytb.config.varible.dao.ConfigGlobalManagementDAO;
import com.jtny.nytb.config.varible.domain.ConfigGlobalManagementDO;
import com.jtny.nytb.config.varible.dto.ConfigGlobalManagementDTO;
import com.jtny.nytb.config.varible.dto.ConfigGlobalPageQueryParamDTO;
import com.jtny.nytb.config.varible.enums.ConfigGlobalManagementEnum;
import com.jtny.nytb.config.varible.service.ConfigGlobalManagementBiz;
import com.jtny.nytb.config.varible.vo.ConfigGlobalManagementFormVO;
import com.jtny.nytb.config.varible.vo.ConfigGlobalManagementQueryVO;
import com.jtny.nytb.config.varible.vo.ConfigGlobalManagementVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * 全局配置管理 Biz 对象
 *
 * @author 智慧能源中心 - 伍天宇
 * @package com.jtny.nytb.config.generic.variable.biz.impl
 * @fileName ConfigGlobalManagementBizImpl.java
 * @createTime 2023年09月05日 15:11
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Service
@AllArgsConstructor
public class ConfigGlobalManagementBizImpl implements ConfigGlobalManagementBiz {
@Autowired
    private ConfigGlobalManagementDAO configGlobalManagementDAO;


    /**
     * 规则配置文件
     */



    /**
     * 分页查询 全局变量管理
     *
     * @param configGlobalManagementQueryVO 查询条件
     * @return {@link PageData}<{@link ConfigGlobalManagementVO}>
     */
    @Override
    public PageData<ConfigGlobalManagementVO> queryPage(ConfigGlobalManagementQueryVO configGlobalManagementQueryVO) {
        ConfigGlobalPageQueryParamDTO configGlobalPageQueryParamDTO = configGlobalManagementQueryVO.buildDto();
        //操作数据库
        PageData<ConfigGlobalManagementDTO> result = queryPage(configGlobalPageQueryParamDTO);
        return result.transformData(ConfigGlobalManagementVO.class);
    }

    /**
     * 保存 全局变量
     *
     * @param configGlobalManagementFormVO 全局变量表单数据
     * @return {@link ConfigGlobalManagementVO}
     */
    @Override
    public void save(ConfigGlobalManagementFormVO configGlobalManagementFormVO) {
        //查询出全部的全局Code 获得Code值最大的那一个，将值加一生成新的Code
        String code = createCode();
        //操作数据库
        save(configGlobalManagementFormVO.buildDto(code));
    }

    /**
     * 更新 全局变量
     *
     * @param configGlobalManagementFormVO 全局变量表单数据
     * @return {@link ConfigGlobalManagementVO}
     */
    @Override
    public void update(ConfigGlobalManagementFormVO configGlobalManagementFormVO) {
        //操作数据库
        update(configGlobalManagementFormVO.buildDto(null));
    }

    /**
     * 依据id获取详情全局变量
     *
     * @param id 主键ID
     * @return {@link ConfigGlobalManagementVO}
     */
    @Override
    public ConfigGlobalManagementVO detail(Long id) {
        //操作数据库
        ConfigGlobalManagementDTO configGlobalManagementDTO = getById(id);
        return BeanUtils.copyToObject(configGlobalManagementDTO, ConfigGlobalManagementVO.class);
    }

    /**
     * 依据id删除全局变量
     *
     * @param id 注解ID
     */
    @Override
    public void deleteById(Long id) {
        //操作数据库
        deleteByAndId(id);
    }

    /**
     * 批量保存
     *
     * @param configGlobalManagementList 全局变量列表
     * @return {@code true} 成功 {@code false} 失败
     */
    @Override
    public Boolean saveBatch(List<ConfigGlobalManagementDTO> configGlobalManagementList) {
        //操作数据库
        return saveAndBatch(configGlobalManagementList);
    }


    private String createCode() {
        List<ConfigGlobalManagementDO> configGlobalManagementDOS = configGlobalManagementDAO.selectList(null);
        if (configGlobalManagementDOS.isEmpty()){
            return "G00001";
        }
        //获取所有Code
        List<String> collect = configGlobalManagementDOS.stream().map(ConfigGlobalManagementDO::getCode).collect(Collectors.toList());
            List<Integer> integerList = collect.stream()
                    .map(code -> {
                        if (code != null && code.length() >= 5) {
                            return Integer.parseInt(code.substring(code.length() - 5));
                        } else {
                            return null; // 或者根据需要处理长度小于5的情况
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            Optional<Integer> max = integerList.stream().max(Integer::compareTo);
            String integer = max.get().toString();
            //保存，新进来的Code加1
            integer=String.valueOf(Integer.parseInt(integer)+1);
            //数字为5位数，不够前
            String stringCode="";
            if (integer.length()!=5){
                int i1 = 5 - integer.length();
                for (int i=0;i<i1;i++){
                    stringCode=stringCode+"0";
                }
            }
            return "G"+stringCode+integer;
        }


    ////////////////////////////////////////////////////
    /**
     * 分页查询 全局变量
     *
     * @param configGlobalPageQueryParamDTO 分页查询参数DTO对象
     * @return {@link PageData}<{@link ConfigGlobalManagementDTO}> 返回全局变量信息分页查询结果PageData对象
     * @throws ServiceException 抛出异常
     */

    public PageData<ConfigGlobalManagementDTO> queryPage(ConfigGlobalPageQueryParamDTO configGlobalPageQueryParamDTO)
            throws ServiceException {
        Assert.notNull(configGlobalPageQueryParamDTO, ConfigGlobalManagementEnum.PARAM_OBJECT_IS_NULL);

        // 封装查询条件QueryWrapper对象
        QueryWrapper<ConfigGlobalManagementDO> queryWrapper = QueryWrapperUtils
                .getQueryWrapper(configGlobalPageQueryParamDTO);
        queryWrapper.orderByDesc("id");

        // 分页查询统一用户信息信息
        Page<ConfigGlobalManagementDO> page = Page
                .of(configGlobalPageQueryParamDTO.getPageNo(), configGlobalPageQueryParamDTO.getPageSize());
        PageData<ConfigGlobalManagementDO> pageData = PageUtils
                .getPageData(configGlobalManagementDAO.selectPage(page, queryWrapper), configGlobalPageQueryParamDTO);

        return pageData.transformData(ConfigGlobalManagementDTO.class);
    }

    /**
     * List查询 全局变量
     *
     * @param configGlobalPageQueryParamDTO 分页查询参数DTO对象
     * @return {@link PageData}<{@link ConfigGlobalManagementDTO}> 返回全局变量信息分页查询结果PageData对象
     * @throws ServiceException 抛出异常
     */

    public List<ConfigGlobalManagementDTO> queryList(ConfigGlobalPageQueryParamDTO configGlobalPageQueryParamDTO) throws ServiceException {
        Assert.notNull(configGlobalPageQueryParamDTO, ConfigGlobalManagementEnum.PARAM_OBJECT_IS_NULL);

        // 封装查询条件QueryWrapper对象
        QueryWrapper<ConfigGlobalManagementDO> queryWrapper = QueryWrapperUtils
                .getQueryWrapper(configGlobalPageQueryParamDTO);
        queryWrapper.orderByDesc("id");

        List<ConfigGlobalManagementDO> doList = configGlobalManagementDAO.selectList(queryWrapper);
        return BeanUtils.copyToList(doList, ConfigGlobalManagementDTO.class);
    }

    /**
     * 保存 全局变量
     *
     * @param configGlobalManagementDTO 全局变量基本信息DTO对象
     * @throws ServiceException 抛出异常
     */

    public void save(ConfigGlobalManagementDTO configGlobalManagementDTO) throws ServiceException {
        Assert.isTrue(checkName(configGlobalManagementDTO.getName(), null), ConfigGlobalManagementEnum.NAME_REPEAT);
//        Assert.isTrue(checkSign(configGlobalManagementDTO.getSign(),null),ConfigGlobalManagementEnum.NAME_REPEAT);
        ConfigGlobalManagementDO toSave = BeanUtils
                .copyToObject(configGlobalManagementDTO, ConfigGlobalManagementDO.class);
        configGlobalManagementDAO.insert(toSave);
    }

    /**
     * 通过主键id获取全局变量信息
     *
     * @param id 主键id
     * @return {@link ConfigGlobalManagementDTO} 全局变量基本信息DTO对象
     * @throws ServiceException 抛出异常
     */

    public ConfigGlobalManagementDTO getById(Long id) throws ServiceException {
        ConfigGlobalManagementDO configGlobalManagementDO = configGlobalManagementDAO.selectById(id);
        return BeanUtils.copyToObject(configGlobalManagementDO, ConfigGlobalManagementDTO.class);
    }

    /**
     * 修改 全局变量
     *
     * @param configGlobalManagementDTO 全局变量基本信息DTO对象
     * @throws ServiceException 抛出异常
     */

    public void update(ConfigGlobalManagementDTO configGlobalManagementDTO) throws ServiceException {
        Assert.isTrue(checkName(configGlobalManagementDTO.getName(), configGlobalManagementDTO.getId()), ConfigGlobalManagementEnum.NAME_REPEAT);
//        Assert.isTrue(checkSign(configGlobalManagementDTO.getSign(),configGlobalManagementDTO.getId()), ConfigGlobalManagementEnum.NAME_REPEAT);
        ConfigGlobalManagementDO toUpdate = BeanUtils.copyToObject(configGlobalManagementDTO, ConfigGlobalManagementDO.class);
        configGlobalManagementDAO.updateById(toUpdate);
    }

    /**
     * 删除 全局变量
     *
     * @param id 主键id
     * @return {@link Boolean} 返回是否正常删除
     * @throws ServiceException 抛出异常
     */

    public Boolean deleteByAndId(Long id) throws ServiceException {
        return SqlHelper.retBool(configGlobalManagementDAO.deleteById(id));
    }

    /**
     * 批量保存
     *
     * @param configGlobalManagementList 配置全局管理列表
     * @return {@link Boolean}
     */

    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAndBatch(List<ConfigGlobalManagementDTO> configGlobalManagementList) {
        if (CollUtil.isNotEmpty(configGlobalManagementList)) {

            List<ConfigGlobalManagementDO> toSaveList = configGlobalManagementList.stream().map(item -> {
                ConfigGlobalManagementDO configGlobalManagementDO = BeanUtils.copyToObject(item, ConfigGlobalManagementDO.class);
                String code = createCode();
                configGlobalManagementDO.setCode(code);
                return configGlobalManagementDO;
            }).collect(Collectors.toList());
            return SqlHelper.retBool(configGlobalManagementDAO.insertBatch(toSaveList));
        }
        return Boolean.FALSE;
    }


//    public ConfigGlobalManagementDTO queryBySign(String sign) throws ServiceException {
//
//        ConfigGlobalManagementDTO configGlobalManagementDTO = new ConfigGlobalManagementDTO();
//        if (sign != null && !sign.trim().equals("")){
//
//            QueryWrapper<ConfigGlobalManagementDO> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("sign",sign);
//            List<ConfigGlobalManagementDO> configGlobalManagementDOS = configGlobalManagementDAO.selectList(queryWrapper);
//
//            if (configGlobalManagementDOS.isEmpty()){
//                throw new ServiceException("未配置全局变量");
//            }
//            if (configGlobalManagementDOS.size() > 1){
//                throw new ServiceException("该全局变量配置过多:" + sign);
//            }
//            BeanUtils.copyObject(configGlobalManagementDOS.get(0),configGlobalManagementDTO);
//        }
//        return configGlobalManagementDTO;
//    }

    /**
     * 校验名称是否重复
     *
     * @param name 名称
     * @param id   主键ID
     * @return {@link Boolean}
     */
    private Boolean checkName(String name, Long id) {
        LambdaQueryWrapper<ConfigGlobalManagementDO> warpper = Wrappers.<ConfigGlobalManagementDO>lambdaQuery()
                .eq(ConfigGlobalManagementDO::getName, name);
        Optional.ofNullable(id).ifPresent(item -> warpper.ne(ConfigGlobalManagementDO::getId, item));
        return !configGlobalManagementDAO.exists(warpper);
    }

//    /**
//     * 校验标识是否重复
//     *
//     * @param sign 标识
//     * @param id   主键ID
//     * @return {@link Boolean}
//     */
//    private Boolean checkSign(String sign, Long id) {
//        LambdaQueryWrapper<ConfigGlobalManagementDO> warpper = Wrappers.<ConfigGlobalManagementDO>lambdaQuery()
//                .eq(ConfigGlobalManagementDO::getSign, sign);
//        Optional.ofNullable(id).ifPresent(item -> warpper.ne(ConfigGlobalManagementDO::getId, item));
//        return !configGlobalManagementDAO.exists(warpper);
//    }

}
